//
//  PTSimplePageHeaderView.m
//  Pods
//
//  Created by aron on 2017/11/23.
//
//

#import "PTSimplePageHeaderView.h"
#import "UIView+PTPageKit.h"
#import "PTPageHeaderModel.h"

#define rectSizeOfString(string, font)  [(string) sizeWithAttributes:@{NSFontAttributeName: (font),}]
#define kIndicatorItemLeftMargin        (21)
#define kIndicatorItemRightMargin       (30)
#define kIndicatorItemMargin            (7)

@interface PTSimplePageHeaderView () <UIScrollViewDelegate>
@property (strong, nonatomic) UIScrollView *scrollView;

@property (strong, nonatomic) NSMutableArray<UIButton *>* buttonArray;
@property (assign, nonatomic) NSInteger currentIndex;

@end

@implementation PTSimplePageHeaderView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.userInteractionEnabled = YES;
        [self addSubview:self.scrollView];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.scrollView.frame = self.bounds;
}

- (void)reloadData {
    if (nil == self.dataSource) {
        return;
    }
    
    if (self.buttonArray.count > 0) {
        [self.buttonArray makeObjectsPerformSelector:@selector(removeFromSuperview)];
    }
    [self.buttonArray removeAllObjects];

    NSInteger buttonCount = [self.dataSource numberOfItemsInHeaderView:self];
    if (buttonCount <= 0) {
        return;
    }
    
    CGFloat buttonWidth = (self.width - kIndicatorItemLeftMargin - kIndicatorItemRightMargin - (buttonCount - 1) * kIndicatorItemMargin) / buttonCount;

    CGFloat totalWidth = 0;
    for (int i = 0; i< buttonCount; i++) {
        PTPageHeaderModel* headerModel = [self.dataSource pageView:self headerItemAtIndex:i];
        UIButton *titleButton = [UIButton buttonWithType:UIButtonTypeCustom];
        titleButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
        [titleButton setTitle:headerModel.title forState:UIControlStateNormal];
        [titleButton setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
        [titleButton setTitleColor:[UIColor colorWithWhite:0.4 alpha:0.9] forState:UIControlStateNormal];
        [titleButton setBackgroundImage:headerModel.normalBgImage forState:UIControlStateNormal];
        [titleButton setBackgroundImage:headerModel.selectedBgImage forState:UIControlStateSelected];
        titleButton.titleLabel.font = [UIFont systemFontOfSize:16];
        // CGFloat buttonWidth = 20 + rectSizeOfString(titleButton.currentTitle, titleButton.titleLabel.font).width;
        titleButton.frame = CGRectMake(0, 0, buttonWidth, self.height);
        
        titleButton.tag = i;
        [self.buttonArray addObject:titleButton];
        totalWidth = totalWidth + titleButton.width;
        [titleButton addTarget:self action:@selector(onTitleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    CGFloat currentOffset = kIndicatorItemLeftMargin;
    for (int i = 0; i < buttonCount; i++) {
        UIButton *button = [self.buttonArray objectAtIndex:i];
        button.frame = CGRectMake(currentOffset, 0, button.width, self.height);
        [self.scrollView addSubview:button];
        currentOffset = currentOffset + button.width + kIndicatorItemMargin;
    }

    self.scrollView.contentSize = CGSizeMake(totalWidth, self.height);
    
    if (self.currentIndex >= 0 && self.currentIndex < buttonCount) {
        [self selectButtonAtIndex:self.currentIndex animated:NO];
    }
}

- (void)onTitleBtnClick:(UIButton*)sender {
    
    if (sender.tag == _currentIndex) {
        return;
    }
    
    [self selectButtonAtIndex:sender.tag animated:YES];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(headerView:didSelectItemAtIndex:)]) {
        [self.delegate headerView:self didSelectItemAtIndex:sender.tag];
    }
}

- (void)selectButtonAtIndex:(NSInteger)index animated:(BOOL)animated {
    UIButton *lastButton = [self.buttonArray objectAtIndex:self.currentIndex];
    [lastButton setSelected:NO];
    
    UIButton *curSelectedButton = [self.buttonArray objectAtIndex:index];
    [curSelectedButton setSelected:YES];
    
    // 更新currentIndex
    self.currentIndex = index;
}


#pragma mark - ......::::::: Override :::::::......

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    for (NSInteger i = self.buttonArray.count - 1; i >= 0; i--) {
        UIView *childView = self.buttonArray[i];
        // 把当前控件上的坐标系转换成子控件上的坐标系
        CGPoint childP = [self convertPoint:point toView:childView];
        UIView *fitView = [childView hitTest:childP withEvent:event];
        if (fitView) {
            // 寻找到最合适的view
            return fitView;
        }
    }
    return nil;
}


#pragma mark - ......::::::: Public :::::::......

- (NSInteger)currentIndex {
    return _currentIndex;
}

/**
 设置按钮选中
 
 @param index 选中按钮的位置
 @param isBackMode 时候背后模式，背后模式选中的隐藏，前台模式选中的显示
 */
- (void)selectButtonAtIndex:(NSInteger)index isBackMode:(BOOL)isBackMode {
    for (int i = 0; i<self.buttonArray.count; i++) {
        UIButton *titleButton = self.buttonArray[i];
        if (i == index) {
            if (isBackMode) {
                titleButton.hidden = YES;
                titleButton.selected = YES;
            } else {
                titleButton.hidden = NO;
                titleButton.selected = YES;
            }
        } else {
            if (isBackMode) {
                titleButton.hidden = NO;
                titleButton.selected = NO;
            } else {
                titleButton.hidden = YES;
                titleButton.selected = NO;
            }
        }
    }
}


#pragma mark - ......::::::: Lazy load :::::::......

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.userInteractionEnabled = YES;
        _scrollView.delegate = self;
        _scrollView.scrollsToTop = NO;
        _scrollView.backgroundColor = [UIColor clearColor];
    }
    return _scrollView;
}

- (NSMutableArray<UIButton *> *)buttonArray {
    if (nil == _buttonArray) {
        _buttonArray = [NSMutableArray arrayWithCapacity:10];
    }
    return _buttonArray;
}

@end
